package com.maori.languageapp.discover.idiom;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import android.view.View.OnFocusChangeListener;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.maori.languageapp.Languageapp_Discover_Videolist_Adapter.ViewHolder;
import com.maori.languageapp.R;
import com.maori.languageapp.consts.ImageLoader;
import com.maori.languageapp.discover.idiom.Maori_Discover_Idiom_Details;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Maori_Discover_Idiom_Details_Adapter extends BaseAdapter {
	private static final String TAG = null;
	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	ImageLoader imageLoader;
	String SYNUserLikedSyn,TotalsSetDefault;
	/*Button setDefAction;
	Button setLikeAction;*/
	int timeoutConnection = 5000;
	int TotalLikesVal;
	HttpParams httpParameters = new BasicHttpParams();
	String SynUserID, SynNodeId, SynParentNodeId,
			SynMediaType;
	private LayoutInflater mInflater;
	InputStream is = null;
	StringBuilder sb = null;
	String result, CurrentUserID,TotalLikes,SYNParentUID;
	int LikeActive = 0;
	int LikeCounter;
	ArrayList<HashMap<String, String>> arraylist;
	JSONArray jsonarray;
	HashMap<String, String> resultp = new HashMap<String, String>();
	
	
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private String LIKESLOG = "LikesLog";

	public Maori_Discover_Idiom_Details_Adapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		 return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		 return position;
	}
	
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		// Declare Variables
		 if (convertView == null) {
		        convertView = mInflater.inflate(R.layout.languageapp_discover_synonyms, null);
		        holder = new ViewHolder();
		        holder.maori_synonym_title = (TextView) convertView.findViewById(R.id.maori_synonym_title);
		        holder.maori_synonym_title = (TextView) convertView.findViewById(R.id.maori_synonym_title);
				holder.english_synonym_title = (TextView) convertView.findViewById(R.id.english_synonym_title);
				holder.dicover_location = (Button) convertView.findViewById(R.id.dicover_location);
				holder.display_dialect = (Button) convertView.findViewById(R.id.display_dialect);
				holder.first_name = (TextView) convertView.findViewById(R.id.first_name);
				holder.last_name = (TextView) convertView.findViewById(R.id.last_name);
				holder.flag = (ImageView) convertView.findViewById(R.id.imggriditem);
				holder.setDefAction = (Button) convertView.findViewById(R.id.setDefAction);
				holder.setLikeAction = (Button) convertView.findViewById(R.id.setLikeAction);
		        convertView.setTag(holder);
		    } else {
		        holder = (ViewHolder) convertView.getTag();
		    }


		resultp = data.get(position);


		// Capture position and set results to the TextViews
		holder.maori_synonym_title.setText(resultp.get(Maori_Discover_Idiom_Details.getDescription_a()));
		holder.english_synonym_title.setText(resultp.get(Maori_Discover_Idiom_Details.getDescription_b()));
		holder.dicover_location.setText(resultp.get(Maori_Discover_Idiom_Details.getSYNcurrent_location()));
		holder.display_dialect.setText(resultp.get(Maori_Discover_Idiom_Details.getSYNdialact()));// SYNtribe
		holder.first_name.setText(resultp.get(Maori_Discover_Idiom_Details.getFirst_namesuser()) + " " + resultp.get(Maori_Discover_Idiom_Details.getLast_nameuser()));
		holder.last_name.setText(resultp.get(Maori_Discover_Idiom_Details.getSYNtribe()));
		String UIDuser = resultp.get(Maori_Discover_Idiom_Details.getUIDuser());
		String SYNNID = resultp.get(Maori_Discover_Idiom_Details.getSYNNID());
		String SYNParentNID = resultp.get(Maori_Discover_Idiom_Details.getSYNParentNID());
		SYNUserLikedSyn = resultp.get(Maori_Discover_Idiom_Details.getSYNUserLikedSyn());
		TotalLikes = resultp.get(Maori_Discover_Idiom_Details.getTotalsLikesSyn());
		CurrentUserID = resultp.get(Maori_Discover_Idiom_Details.getSYNParentUID());
		TotalsSetDefault = resultp.get(Maori_Discover_Idiom_Details.getTotalsSetDefault());

		if(TotalsSetDefault.equals("0")){
			holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_inactive, 0, 0, 0);
		}
		else{
			holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
		}
		
		
		if (SYNUserLikedSyn.equals("0")) {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_inactive_h, 0, 0, 0);
		} else {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_h, 0, 0, 0);
		}

		holder.setLikeAction.setText("Like(" + TotalLikes + ")");

		imageLoader.DisplayImage(resultp.get(Maori_Discover_Idiom_Details.getUserimageuser()), holder.flag);

		holder.setLikeAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				resultp = data.get(position);
				//SYNUserLikedSyn = resultp.get(Maori_Discover_Idiom_Details.getSYNUserLikedSyn());
				TotalLikes = resultp.get(Maori_Discover_Idiom_Details.getTotalsLikesSyn());
				SynUserID = resultp.get(Maori_Discover_Idiom_Details.getUIDuser());
				SynNodeId = resultp.get(Maori_Discover_Idiom_Details.getSYNNID());
				SynParentNodeId = resultp.get(Maori_Discover_Idiom_Details.getSYNParentNID());
				SYNUserLikedSyn = resultp.get(Maori_Discover_Idiom_Details.getSYNUserLikedSyn());
				SYNParentUID = resultp.get(Maori_Discover_Idiom_Details.getSYNParentUID());
				TotalLikesVal = Integer.parseInt(TotalLikes);
				
				JSONObject infomainSegments = new JSONObject();
				
				
				
				Log.v("TAG 1: ", "LIKE STATE**********: " + SYNUserLikedSyn);
				Log.v("TAG 2: ", "LIKE TOTAL**********: " + TotalLikesVal);
				Log.v("TAG 3: ", "LIKE NODE***********: " + SynNodeId);
				
				if(SYNUserLikedSyn.equals("0")){
					SYNUserLikedSyn = "1";
					holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_h, 0, 0, 0);
					TotalLikesVal = TotalLikesVal + 1;
					TotalLikes = "" + TotalLikesVal;
					holder.setLikeAction.setText("Like(" + TotalLikesVal + ")");
					
					//Update Values Of the Hash Map Position
					resultp.put("TotalsLikesSyn", TotalLikes);
					resultp.put("SYNUserLikedSyn", SYNUserLikedSyn);
				}
				else {
					SYNUserLikedSyn = "0";
					holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_inactive, 0, 0, 0);
					TotalLikesVal = TotalLikesVal - 1;
					TotalLikes = "" + TotalLikesVal;
					holder.setLikeAction.setText("Like(" + TotalLikesVal + ")");
					//Update Values Of the Hash Map Position
					resultp.put("TotalsLikesSyn", TotalLikes);
					resultp.put("SYNUserLikedSyn", SYNUserLikedSyn);
				}
				new UploadLikeStateDetails().execute();
			
				
			}
		});

		holder.setDefAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				TotalsSetDefault = resultp.get(Maori_Discover_Idiom_Details.getTotalsSetDefault());

				if(TotalsSetDefault.equals("0")){
					holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
				}
				else{
					holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_inactive, 0, 0, 0);
				}
				resultp = data.get(position);
				SynUserID = resultp.get(Maori_Discover_Idiom_Details.getUIDuser());
				SynNodeId = resultp.get(Maori_Discover_Idiom_Details.getSYNNID());
				SynParentNodeId = resultp
						.get(Maori_Discover_Idiom_Details.getSYNParentNID());
				SynMediaType = "0";
				
				
				new UploadSetDefaultDetails().execute();
			}
		});
		
		
		/* holder.setLikeAction.setId(position);
	        //we need to update adapter once we finish with editing
	        holder.setLikeAction.setOnFocusChangeListener(new OnFocusChangeListener() {
	            public void onFocusChange(View v, boolean hasFocus) {
	                if (!hasFocus){
	                    final int position = v.getId();
	                    final Button Caption = (Button) v;
	                    HashMap<String, String> map = new HashMap<String, String>();
	                    map.put("TotalsLikesSyn", Caption.getText().toString());
	                    arraylist.set(position, map);
	                }
	            }
	        });
		*/
		
		return convertView;
	}
	static class ViewHolder {
		TextView maori_synonym_title;
		TextView english_synonym_title;
		TextView first_name; 
		TextView last_name;
		Button display_dialect;
		Button dicover_location;
		Button setDefAction;
		Button setLikeAction;
		ImageView flag;
	}
	private class UploadSetDefaultDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/saveUsersSetDefaults.php");
				// Selected Type ID / content_type_id
				json.put("record1", CurrentUserID);
				// Selected UID / added_by
				json.put("record2", SynNodeId);

				json.put("record3", SynMediaType);

				json.put("record4", SynParentNodeId);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.v("TAG","POST SET DEF : " + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v("TAG", "Print Res***:" + result);
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			Intent intent = new Intent(context,
					Maori_Discover_Idiom_Details.class);
			intent.putExtra("nid", SynParentNodeId);
			context.startActivity(intent);
			((Maori_Discover_Idiom_Details)context).finish();
		}
	}

	/*********************************************/
	private class UploadLikeStateDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/saveNodeLike.php");
				// Selected Type ID / content_type_id
				Log.e("SYN", "NID : " + SynNodeId);
				Log.e("SYN", "UID : " + CurrentUserID);

				json.put("record1", SynNodeId);
				// Selected UID / added_by
				json.put("record2", CurrentUserID);

				json.put("record3", "0");

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v("TAG", "RES :" + result);
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			/*Log.v("LIKE RES ", ":" + result);
			Intent intent = new Intent(context,
					Maori_Discover_Idiom_Details.class);
			intent.putExtra("nid", SynParentNodeId);
			context.startActivity(intent);*/
			if (result != null) {
				arraylist = new ArrayList<HashMap<String, String>>();
				try {
					JSONObject jsonObj = new JSONObject(result);
					jsonarray = jsonObj.getJSONArray("posts");
					for (int i = 0; i < jsonarray.length(); i++) {
						JSONObject c = jsonarray.getJSONObject(i);
						HashMap<String, String> map = new HashMap<String, String>();
						String LikeCount = c.getString("TotalsLikesSyn");
						String ActiveState = c.getString("LikeActive");
						//TotalLikes = "99";
					/*	if (ActiveState.equals("100")) {
							SYNUserLikedSyn = "0";
							resultp.put(resultp.get(Maori_Discover_Idiom_Details.getSYNUserLikedSyn()), SYNUserLikedSyn);
							resultp.put(resultp.get(Maori_Discover_Idiom_Details.getTotalsLikesSyn()), LikeCount);
						}

						else {
							SYNUserLikedSyn = "1";
							resultp.put(resultp.get(Maori_Discover_Idiom_Details.getSYNUserLikedSyn()), SYNUserLikedSyn);
							resultp.put(resultp.get(Maori_Discover_Idiom_Details.getTotalsLikesSyn()), LikeCount);
						}*/

					}
				} catch (Exception e) {

				}

			}

		}
	}
}
